<template>

  <div class="app-container">
    <div>
      <el-form inline :model="formParams">
        <!-- 期数选择 -->
        <el-form-item label="期数" prop="settingDate" required>
          <el-date-picker
              style="width: 150px"
              v-model="formParams.settingDate"
              type="month"
              placeholder="选择年月"
              format="YYYY-MM"
              value-format="YYYY-MM"
              class="full-width"
          />
        </el-form-item>
        <!-- 期数选择 -->
        <el-form-item label="起始日期" prop="settingDateStart">
          <el-date-picker
              style="width: 150px"
              v-model="formParams.settingDateStart"
              type="date"
              placeholder="选择年月日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="full-width"
              @change="handleSettingDateChange"
          />
        </el-form-item>
        <!-- 期数选择 -->
        <el-form-item label="结束日期" prop="settingDateEnd">
          <el-date-picker
              style="width: 150px"
              v-model="formParams.settingDateEnd"
              type="date"
              placeholder="选择年月日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="full-width"
              @change="handleSettingDateChange"
          />
        </el-form-item>

        <!-- 客户名称（可搜索下拉框） -->
        <el-form-item label="客户名称" prop="clientId">
          <el-select
              style="width: 200px"
              v-model="formParams.clientId"
              filterable
              clearable
              placeholder="搜索客户"
              class="full-width"
              @change="handleClientChange"
          >
            <el-option
                v-for="item in clientSelection"
                :key="item.traderid"
                :label="item.name"
                :value="item.traderid"
            />
          </el-select>
        </el-form-item>
        <!-- 结算单位（可搜索下拉框） -->
        <el-form-item label="结算单位" prop="accountId">
          <el-select
              style="width: 200px"
              v-model="formParams.accountId"
              filterable
              clearable
              placeholder="搜索结算单位"
              class="full-width"
          >
            <el-option
                v-for="item in showSettlementUnitSelection"
                :key="item.accountId"
                :label="item.accountName"
                :value="item.accountId"
            />
          </el-select>
        </el-form-item><!-- 结算单位（可搜索下拉框） -->
        <el-form-item label="已返点" prop="rebateStatus">
          <el-select
              style="width: 80px"
              v-model="formParams.rebateStatus"
              filterable
              clearable
              placeholder=""
              class="full-width"
              @change="handleRebateStatusChange"
          >
            <el-option
                v-for="item in rebateStatusOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="已匹配" prop="matchStatus">
          <el-select
              style="width: 80px"
              v-model="formParams.matchStatus"
              filterable
              clearable
              placeholder=""
              class="full-width"
          >
            <el-option
                v-for="item in matchStatusOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="返点单位" prop="rebateClientId" required>
          <el-select
              style="width: 200px"
              v-model="formParams.rebateClientId"
              filterable
              clearable
              placeholder="搜索返点单位"
              class="full-width"
          >
            <el-option
                v-for="item in rebateClientOptions"
                :key="item.traderid"
                :label="item.name"
                :value="item.traderid"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleList" type="primary" class="add-btn">
            <el-icon>
              <Search/>
            </el-icon>
            查询
          </el-button>
          <el-button @click="handleReferralBonus" type="primary" class="create-btn">
            <el-icon>
              <EditPen/>
            </el-icon>
            返点
          </el-button>
          <el-dropdown style="margin-left: 10px" @command="handleCommand">
            <el-button type="primary" class="create-btn">
              预览<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="a">销售折让通知单</el-dropdown-item>
              </el-dropdown-menu>
              <el-dropdown-menu>
                <el-dropdown-item command="b">销售返点汇总表</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <!--      <el-button @click="handleSubmit" type="primary">提交</el-button>-->
          <!--      <el-button @click="handleExport" type="warning">导出</el-button>-->
        </el-form-item>
      </el-form>
    </div>
    <div class="center">
      <el-table ref="tableRef" :data="tableData" :summary-method="getSummaries" show-summary style="width: 100%" border height="100%"
                @selection-change="handleSelectionChange" @row-click="handleRowClick" v-loading="loading"
                :cell-style="cellStyle" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column type="selection" width="40" fixed/>
        <el-table-column type="index" width="55" label="序号" align="center"  fixed/>
        <el-table-column v-for="item in columns" :key="item.prop" :property="item.prop" :label="item.label"
                         :width="item.width"></el-table-column>
      </el-table>
      <div>
        <el-pagination style="float: right; margin-top: 10px;" v-model:current-page="currentPage"
                       v-model:page-size="pageSize" :page-sizes="[50, 100, 150, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" background/>
      </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="title"
        width="600px"
        @closed="resetForm"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          label-position="left"
          class="custom-form"
      >
        <!-- 期数选择 -->
        <el-form-item label="期数" prop="settingDate">
          <el-date-picker
              v-model="formData.settingDate"
              type="month"
              placeholder="选择年月"
              format="YYYY-MM"
              value-format="YYYY-MM"
              class="full-width"
          />
        </el-form-item>

        <!-- 客户名称（可搜索下拉框） -->
        <el-form-item label="客户名称" prop="clientId">
          <el-select
              v-model="formData.clientId"
              filterable
              reserve-keyword
              placeholder="搜索客户"
              class="full-width"
          >
            <el-option
                v-for="item in clientSelection"
                :key="item.traderid"
                :label="item.name"
                :value="item.traderid"
            />
          </el-select>
        </el-form-item>

        <!-- 纸张类型（可搜索下拉框） -->
        <el-form-item label="纸张类型" prop="paperType">
          <el-input
              v-model="formData.paperType"
              class="full-width"
              placeholder="纸张类型"></el-input>
        </el-form-item>

        <!-- 返点单价（带单位数字输入） -->
        <el-form-item label="返点单价" prop="unitPrice">
          <el-input-number
              v-model="formData.unitPrice"
              :min="0"
              :precision="2"
              :step="0.1"
              controls-position="right"
              class="price-input"
          />
          <span class="unit">元/吨</span>
        </el-form-item>

        <!-- 结算单位（可搜索下拉框） -->
        <el-form-item label="结算单位" prop="unitOfAccount">
          <el-select
              v-model="formData.unitOfAccount"
              filterable
              placeholder="结算单位"
              class="full-width"
          >
            <el-option
                v-for="item in clientSelection"
                :key="item.traderid"
                :label="item.name"
                :value="item.traderid"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, computed} from "vue";
import request from '../../utils/request'
import {useLoading} from '../../utils/loading'
import {ElMessage, ElNotification} from 'element-plus'


import {useStore} from "vuex";

const store = useStore()
const username = computed(() => store.state.auth.user)

const tableData = ref()
const loading = ref(false)
// 表单数据
const formData = ref({
  settingDate: '',
  settingDateStart: '',
  settingDateEnd: '',
  clientId: '',
  paperType: '',
  unitPrice: 0,
  unitOfAccount: ''
})

// 表单引用
const formRef = ref(null)

// 对话框可见性
const dialogVisible = ref(false)


// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
const cellStyle = ({row}) => {
  if (row.targetBillcode) return {color: 'black'}        // targetBillcode不为空 → 黑色
  if (!row.paperType) return {color: 'black'}             // paperType为空 → 红色
  return {color: 'green'}                               // 其他 → 绿色
}
// 表单验证规则
const rules = reactive({
  settingDate: [
    {required: true, message: '请选择期数', trigger: 'blur'}
  ],
  clientId: [
    {required: true, message: '请选择客户名称', trigger: 'change'}
  ],
  paperType: [
    {required: true, message: '请选择纸张类型', trigger: 'change'}
  ],
  unitPrice: [
    {required: true, message: '请输入返点单价', trigger: 'blur'},
    {type: 'number', min: 0, message: '单价不能为负数', trigger: 'blur'}
  ],
  unitOfAccount: [
    {required: true, message: '请选择结算单位', trigger: 'change'}
  ]
})

const rebateStatusOptions = ref(['是','否'])
const matchStatusOptions = ref(['是','否'])

const url = {
  listUrl: '/salesRebateInventory/list',
  querySelectionUrl: '/salesRebateSetting/querySelection',
  querySettingDateUrl: '/salesRebateInventory/querySettingDate',
  submitUrl: '/salesRebateInventory/submit',
  referralBonusUrl: '/salesRebateInventory/referralBonus',
  queryRebateClientUrl: '/salesRebateSetting/queryRebateClient',
}

const handleCommand = (command: string | number | object) => {
  if (command == 'a'){
    window.open('http://192.168.0.223:8080/webroot/decision/view/report?viewlet=DQ/LianGuiRebate.cpt' +
        '&QS=' + (formParams.value.settingDate ? formParams.value.settingDate : '') +
        '&QSRQ=' + (formParams.value.settingDateStart ? formParams.value.settingDateStart : '') +
        '&JSRQ=' + (formParams.value.settingDateEnd ? formParams.value.settingDateEnd : '') +
        '&KH=' + (formParams.value.clientId ? formParams.value.clientId : '') +
        '&JSDW=' + (formParams.value.accountId ? formParams.value.accountId : '') +
        '&FDDW=' + (formParams.value.rebateClientId ? formParams.value.rebateClientId : '')
    )
  } else if (command == 'b') {
    window.open('http://192.168.0.223:8080/webroot/decision/view/report?viewlet=DQ/LianGuiRebateClientCollect.cpt')
  }
}
const columns = [{
  prop: 'billDate',
  label: '销售日期',
  width: '100'
}, {
  prop: 'billCode',
  label: '销售单号',
  width: '150'
}, {
  prop: 'clientName',
  label: '客户',
  width: '150'
}, {
  prop: 'goodsName',
  label: '货品名称',
  width: '250'
}, {
  prop: 'paperType',
  label: '纸张类型',
  width: '120'
}, {
  prop: 'quantity',
  label: '重量(KG)',
  width: '100'
}, {
  prop: 'unitPrice',
  label: '单价(元/吨)',
  width: '100'
}, {
  prop: 'amount',
  label: '金额',
  width: '100'
}, {
  prop: 'accountName',
  label: '结算单位',
  width: '150'
}, {
  prop: 'targetBillcode',
  label: '返点单号',
  width: '150'
}, {
  prop: 'matchStatus',
  label: '匹配状态',
  width: '100'
}, {
  prop: 'rebateStatus',
  label: '返点状态',
  width: '100'
}]

const title = ref('新增')

const handleEdit = (row) => {
  title.value = '编辑'
  formData.value = row
  dialogVisible.value = true
}

const handleSettingDateChange = () => {
  httpQuerySelection()
}
const handleClientChange = (val) => {
  showSettlementUnitSelection.value = settlementUnitSelection.value.filter(item => item.clientId === val);
  formParams.value.accountId = null
  formParams.value.rebateClientId = val
}

const handleRebateStatusChange = (val) => {
  if (val == '是') {
    formParams.value.matchStatus = '是'
  }
}

// 获取上个月的第一天（格式：YYYY-MM-DD）
const getFirstDayOfLastMonth = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth(); // 注意：月份从0开始

  // 处理跨年（1月时上个月是去年的12月）
  const lastMonthYear = (month === 0) ? year - 1 : year;
  const lastMonth = (month === 0) ? 11 : month - 1;

  // 格式化为 YYYY-MM-DD
  return `${lastMonthYear}-${String(lastMonth + 1).padStart(2, '0')}-01`;
};

// 获取上个月的最后一天（格式：YYYY-MM-DD）
const getLastDayOfLastMonth = () => {
  const lastDay = new Date(new Date().getFullYear(), new Date().getMonth(), 0);
  const year = lastDay.getFullYear();
  const month = String(lastDay.getMonth() + 1).padStart(2, '0'); // 月份+1补零
  const day = String(lastDay.getDate()).padStart(2, '0'); // 直接取本地日期
  return `${year}-${month}-${day}`; // 格式：YYYY-MM-DD
};

// 获取上个月的月份（格式：YYYY-MM）
const getLastMonth = () => {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth(); // 当前月份索引（0-11）

  if (month === 0) { // 1月时上个月是去年12月
    year -= 1;
    month = 11;
  } else {
    month -= 1;
  }

  return `${year}-${String(month + 1).padStart(2, '0')}`;
};

const rebateClientOptions = ref()
const httpQueryRebateClient = () => {
  request({
    url: url.queryRebateClientUrl,
    method: 'get'
  }).then(res => {
    rebateClientOptions.value = res.data
  })
}

// 生命周期钩子：组件挂载时获取数据
onMounted(async () => {
  tableHeight.value = window.innerHeight - 300

  httpQueryRebateClient()
  formParams.value.settingDate = getLastMonth()
  formParams.value.settingDateStart = getFirstDayOfLastMonth()
  formParams.value.settingDateEnd = getLastDayOfLastMonth()
  formParams.value.rebateStatus = '否'
  formParams.value.matchStatus = '否'
  handleList()
  httpQuerySelection()
})


const clientSelection = ref(null);
const showClientSelection = ref(null);
const goodsSelection = ref(null);
const settlementUnitSelection = ref(null);
const showSettlementUnitSelection = ref(null);
const httpQuerySelection = () => {
  request({
    url: url.querySelectionUrl,
    method: 'get',
    params: {
      startDate: formParams.value.settingDateStart,
      endDate: formParams.value.settingDateEnd
    }
  }).then(response => {
    goodsSelection.value = response.data.goodsSelection
    clientSelection.value = response.data.clientSelection
    showClientSelection.value = response.data.clientSelection
    settlementUnitSelection.value = response.data.settlementUnitSelection
  }).catch(err => {
    console.log('err', err)
  }).finally(() => {
  })
}
// 分页
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(150)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleList()
}

// 多选
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const tableRef = ref();
const handleRowClick = (row) => {
  tableRef.value.toggleRowSelection(row); // 切换当前行选中状态
};


const tableHeight = ref(0);
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const loading = useLoading()
      request({
        url: url.submitUrl,
        method: 'post',
        params: {
          username: username.value,
        },
        data: formData.value
      }).then(res => {
        if (res.code == 200) {
          dialogVisible.value = false
          ElNotification.success({title: '成功提示', message: '提交成功'})
          handleList()
          return
        }
        ElNotification.error({title: '错误提示', message: res.message})
      }).catch(err => {
        ElNotification.error({title: '错误提示', message: err.message})
      }).finally(() => {
        loading.close()
      })
    } else {
      ElMessage.warning('请填写完整的表单信息')
    }
  })
}

const handleReferralBonus = () => {
  if (multipleSelection.value.length <= 0) {
    ElNotification.warning({
      title: '提示',
      message: '请选择记录'
    })
    return;
  }
  if (!formParams.value.rebateClientId) {
    ElNotification.warning({
      title: '提示',
      message: '请选择返点单位'
    })
    return;
  }
  if (!formParams.value.settingDate) {
    ElNotification.warning({
      title: '提示',
      message: '请选择期数'
    })
    return;
  }
  const loading = useLoading()
  request({
    url: url.referralBonusUrl,
    method: 'post',
    data: multipleSelection.value,
    params: {
      username: username.value,
      rebateClientId: formParams.value.rebateClientId,
      month: formParams.value.settingDate
    }
  }).then(res => {
    if (res.code == 200) {
      ElNotification.success({
        title: '提示',
        message: '返点成功'
      })
      handleList()
      return
    }
    ElNotification.warning({
      title: '错误提示',
      message: res.message
    })
  }).catch((err) => {
    ElNotification.warning({
      title: '错误提示',
      message: err
    })
  }).finally(() => {
    loading.close()
  })
}

// 自定义合计方法 - 核心逻辑
function getSummaries(param) {
  const { columns, data } = param;
  const sums = [];

  columns.forEach((column, index) => {
    if (index === 2) {
      // 第一列显示"合计"字样
      sums[index] = multipleSelection.value.length > 0 ? '合计' : '';
      return;
    }

    // 只计算quantity(重量)和amount(金额)两列
    if (column.property === 'quantity' || column.property === 'amount') {
      // 如果没有选中行，则对应列不显示合计
      if (multipleSelection.value.length === 0) {
        sums[index] = '';
        return;
      }

      // 提取选中行中当前列的数据
      const values = multipleSelection.value.map(item => Number(item[column.property]));

      // 计算合计值
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);

        // 重量取整，金额保留两位小数
        sums[index] = column.property === 'quantity'
            ? Math.round(sums[index])
            : sums[index].toFixed(2);
      }
    } else {
      sums[index] = '';
    }
  });

  return sums;
}
// const getSummaries = (param) => {
//   const { columns, data } = param;
//   const sums = [];
//   columns.forEach((column, index) => {
//     if (index === 2) {
//       sums[index] = "合计";
//       return;
//     }
//
//     // 只计算重量(quantity)和金额(amount)
//     if (column.property === 'quantity' || column.property === 'amount') {
//       const values = data.map(item => Number(item[column.property]));
//       if (!values.every(value => isNaN(value))) {
//         sums[index] = values.reduce((prev, curr) => {
//           const value = Number(curr);
//           return !isNaN(value) ? prev + curr : prev;
//         }, 0);
//
//         // 重量保留整数，金额保留两位小数
//         sums[index] = column.property === 'quantity'
//             ? Math.round(sums[index])
//             : sums[index].toFixed(2);
//       }
//     } else {
//       sums[index] = '';
//     }
//   });
//   return sums;
// };

const formParams = ref({})
const handleList = async () => {
  try {

    loading.value = true
    request({
      url: url.listUrl,
      method: 'get',
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        ...formParams.value
      }
    }).then(response => {
      tableData.value = response.data
      total.value = response.total
    }).finally(() => {
      loading.value = false
    })
  } catch (error) {
    console.log('error', error)
  }
}

</script>

<style scoped>
.container {
  padding: 20px;
}

.add-btn {
  background: linear-gradient(135deg, #409eff, #79bbff);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.copy-btn {
  background: linear-gradient(135deg, #71714a, #eeb936);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}


.copy-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}


.create-btn {
  background: linear-gradient(135deg, #71714a, #57b237);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}


.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.custom-form {
  padding: 20px 30px;
  border-radius: 12px;
  background: #f8fafc;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.full-width {
  width: 100%;
}

.price-input {
  width: 180px;
  margin-right: 10px;
}

.unit {
  color: #606266;
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #344758;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  height: 33px;
  line-height: 33px;
}

:deep(.el-select .el-input__inner) {
  cursor: pointer;
}

.el-popper {
  border-radius: 8px !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1) !important;
}

.el-select-dropdown__item {
  /*padding: 10px 20px !important;*/
  font-size: 14px;
}

.el-select-dropdown__item:hover {
  background-color: #f5f7fa !important;
}

.el-date-picker {
  border-radius: 8px !important;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1) !important;
}

.el-dialog {
  border-radius: 12px !important;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #409eff, #79bbff);
  margin: 0 !important;
  padding: 16px 20px !important;
}

.el-dialog__title {
  color: white !important;
  font-weight: 600;
}

.el-dialog__headerbtn .el-dialog__close {
  color: white !important;
}

.center {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.app-container {
  padding: 0px;
  height: calc(100vh - 164px);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

:deep(.el-table__header th:hover) {
  background: #ebf5ff !important;
  transition: background 0.3s;
}

/* 合计行样式 */
:deep(.el-table__footer) td {
  background-color: #f5f7fa !important;
  font-weight: bold;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

/* 调整固定列在合计行的显示 */
:deep(.el-table__fixed-footer-wrapper) {
  bottom: 0 !important;
  background-color: #f5f7fa;
}
</style>
